﻿#include "OpenGLTextureBuffer.h"

using namespace Kriko;

OpenGLTextureBuffer::OpenGLTextureBuffer(const Texture& texture)
{
    glGenTextures(1, &textureBufferID);
    Bind();
    GLenum format;
    if (texture.m_channels == 1)
        format = GL_RED;
    else if (texture.m_channels == 3)
        format = GL_RGB;
    else if (texture.m_channels == 4)
        format = GL_RGBA;
    glTexImage2D(GL_TEXTURE_2D, 0, format, texture.m_width, texture.m_height, 0, format, GL_UNSIGNED_BYTE, texture.m_data);
    glGenerateMipmap(GL_TEXTURE_2D);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    Unbind();
}

OpenGLTextureBuffer::OpenGLTextureBuffer(size_t width, size_t height)
{
    Texture texture;
    texture.m_width = width;
    texture.m_height = height;

    glGenTextures(1, &textureBufferID);
    glBindTexture(GL_TEXTURE_2D, textureBufferID);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureBufferID, 0);
}

OpenGLTextureBuffer::~OpenGLTextureBuffer()
{
    glDeleteTextures(1, &textureBufferID);
}



void OpenGLTextureBuffer::Bind(int index)
{
    glActiveTexture(GL_TEXTURE0 + index);
    glBindTexture(GL_TEXTURE_2D, textureBufferID);
}

void OpenGLTextureBuffer::Unbind()
{
    glBindTexture(GL_TEXTURE_2D, 0);
}

